<?php

namespace app\services;

use app\utils\Jwt;
use support\Container;

abstract class BaseService
{
    protected $dao;

    /**
     * 获取分页配置
     * @param bool $isPage
     * @param bool $isRelieve
     * @return int[]
     */
    public function getPageValue(bool $isPage = true, bool $isRelieve = true): array
    {
        $page = $limit = 0;
        if ($isPage) {
            $request = request();
            $page = $request->input('page', 0);
            $limit = $request->input('limit', 10);
        }
        $limitMax = 20;
        $defaultLimit = 10;
        if ($limit > $limitMax && $isRelieve) {
            $limit = $limitMax;
        }
        return [(int)$page, (int)$limit, (int)$defaultLimit];
    }

    /**
     * 密码hash加密
     * @param string $password
     * @return false|string|null
     */
    public function passwordHash(string $password)
    {
        return password_hash($password, PASSWORD_BCRYPT);
    }

    /**
     * tree处理 分类、标签数据(这一类数据)
     * @param array $cate
     * @param array $label
     * @return array
     */
    public function get_tree_children(array $cate, array $label)
    {
        if ($cate) {
            foreach ($cate as $key => $value) {
                if ($label) {
                    foreach ($label as $k => $item) {
                        if ($value['id'] == $item['label_cate']) {
                            $cate[$key]['children'][] = $item;
                            unset($label[$k]);
                        }
                    }
                } else {
                    $cate[$key]['children'] = [];
                }
            }
        }
        return $cate;
    }

    /**
     * 文字格式转utf8
     * @param $str
     * @return array|false|string|string[]|null
     */
    public function strToUtf8($str)
    {
        $encode = mb_detect_encoding($str, array("ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5'));
        if ($encode == 'UTF-8') {
            return $str;
        } else {
            return mb_convert_encoding($str, 'UTF-8', $encode);
        }
    }

    /**
     * 生成token
     * @param int $id
     * @param $type
     * @param string $pwd
     * @return mixed
     */
    public function createToken(int $id, $type, string $pwd = '')
    {
        $jwtAuth = Container::get(Jwt::class);
        return $jwtAuth->createToken($id, $type, ['auth' => md5($pwd)]);
    }


}
